import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/media_asset_data_entity.dart';
import 'package:lcapp/data/xian_huo_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/oss/oss.dart';
import 'package:lcapp/model/param/base_param.dart';
import 'package:lcapp/model/permission/permission_operate.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/widget/asr_app_bar.dart';
import 'package:lcapp/widget/asr_cache_image.dart';

class FabuVideoPage extends StatefulWidget {
  const FabuVideoPage({Key? key}) : super(key: key);

  @override
  _FabuVideoPageState createState() => _FabuVideoPageState();
}

class _FabuVideoPageState extends State<FabuVideoPage> {
  TextEditingController controller = TextEditingController();

  XianHuoDataEntity xhEntity=XianHuoDataEntity();
  List<MediaAssetDataEntity>? assets = [];
  StreamSubscription? _subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      getVideo();
    });
    _subscription = eventBus.on<OssUploadState>().listen((event) {
      if (event.state == 1 && event.type == 2) {
        saveVideo(event.assets);
      }
    });
  }

  getVideo(){
    // getAlbumPermission(context, ()async{
    //   List<MediaAssetDataEntity> videos = await AsrMediaPicker.pickVideo(
    //       maxDuration: 120,showCamera: true,compressSize:200
    //   );
    //   if(videos.isNotEmpty){
    //     setState(() {
    //       assets = videos;
    //     });
    //   }
    // });
  }

  saveVideo(List<MediaAssetDataEntity> assets)async{
    print('assets===='+assets[0].toJson().toString());
    Map<String,dynamic> body = {
      'coverPath':assets[0].url!+'?x-oss-process=video/snapshot,t_1000,m_fast',
      'video_Desc':controller.text,
      'duration':assets[0].videoDuration,
      'goods_Id':xhEntity.id,
      'video_url':assets[0].url,
      'mediaId':assets[0].mediaId
    };
    showLoading();
    ResponseData res = await HomeAPI.saveVideo(body);
    hideLoading();
    if(res.code==200){
      showToast('发布成功');
      eventBus.fire(FabuState(0));
      Navigator.of(context).pop();
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 1.sw,
      height: 1.sh,
      child: Stack(
        children: [
          Scaffold(
            backgroundColor: bgColor,
            appBar: AsrAppBar(
              titleText: '发布视频',
              barColor: Colors.white,
              backgroundColor: defaultBarColor,
            ),
            body: Container(
              child: GestureDetector(
                onTap: (){
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                child: Column(
                  children: [
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.all(30.w),
                      child: Row(
                        children: [
                          Expanded(child: Container(
                            height: 380.w,
                            child: TextField(
                              controller: controller,
                              maxLines: null,
                              keyboardType: TextInputType.multiline,
                              decoration:  InputDecoration(
                                contentPadding: EdgeInsets.only(left: 17.w),
                                hintText: "添加作品描述..",
                                hintStyle: TextStyle(
                                  color: const Color(0xFF7F7F7F),
                                  fontSize: 26.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                                counterText: "",
                                border: const OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                                fillColor: Colors.transparent,
                                filled: true,
                              ),
                            ),
                          )),
                          SizedBox(width: 40.w,),
                          GestureDetector(
                            onTap: (){
                              getVideo();
                            },
                            child: Container(
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(10.w),
                                  child: assets!.isNotEmpty? Stack(
                                    children: [
                                      ASRCacheImage(
                                        fit: BoxFit.cover,
                                        height: 380.w,
                                        width: 220.w,
                                        image: assets!.isNotEmpty? assets![0].videoCoverUri!:'',
                                      ),
                                      Positioned(child: Container(
                                        height: 56.w,
                                        color: Color(0x6f000000),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Icon(Icons.refresh,color: Colors.white,size: 30.w,),
                                            Text('重新上传',style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 26.sp
                                            ),)
                                          ],
                                        ),
                                      ),left: 0,right: 0,bottom: 0,)
                                    ],
                                  ):Container(
                                    height: 380.w,
                                    width: 220.w,
                                    color: Color(0xffF7F7F7),
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Icon(Icons.add,color: defaultBarColor,size: 100.sp,),
                                        SizedBox(height: 20.w,),
                                        Text('选择视频',style: TextStyle(
                                            color: Color(0xff444444),
                                            fontSize: 26.sp
                                        ),)
                                      ],
                                    ),
                                  ),
                                )
                            ),
                          )
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        FocusScope.of(context).requestFocus(FocusNode());
                        Navigator.of(context).pushNamed("ChooseXianHuoPage").then((value){
                          if(value is XianHuoDataEntity){
                            setState(() {
                              xhEntity = value;
                            });
                          }
                        });
                      },
                      child: Container(
                        height: 100.w,
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        margin: EdgeInsets.symmetric(vertical: 30.w,horizontal: 30.w),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10.w)
                        ),
                        child: xhEntity.id==null? Row(
                          children: [
                            Image.asset('assets/fabu/fabu_add.png',width: 30.w,),
                            SizedBox(width: 10.w,),
                            Text('添加现货信息',style: TextStyle(
                                color: Color(0xff444444),
                                fontSize: 26.sp
                            ),)
                          ],
                        ):Row(
                          children: [
                            Container(
                              child: ClipRRect(
                                child: ASRCacheImage(image:xhEntity.images!=null&&xhEntity.images!.isNotEmpty?xhEntity.images![0]:"assets/home/home_xiaomai.png",width: 60.w,height:60.w,fit: BoxFit.fill,),
                                borderRadius: BorderRadius.circular(10.w),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 20.w),
                              height: 30.w,
                              width: 1.w,
                              color: Colors.white,
                            ),
                            Container(
                              child: Text('${xhEntity.name} ${xhEntity.production}',style:TextStyle(
                                  color: Color(0xff444444),
                                  fontSize: 26.sp,
                                  fontWeight: FontWeight.w500
                              ),),
                            )
                          ],
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        FocusScope.of(context).requestFocus(FocusNode());
                        if(assets!.isEmpty){
                          showToast('请先选择视频');
                          return;
                        }
                        RegExp exp = RegExp(
                            r'((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}');
                        RegExpMatch? matchs = exp.firstMatch(controller.text);
                        if(matchs!=null){
                          showToast('请不要输入手机号登敏感信息!');
                          return;
                        }
                        // AsrOss.ossUploadVideo(assets,type: 2);
                      },
                      child: Container(
                        height: 100.w,
                        margin: EdgeInsets.symmetric(horizontal: 30.w),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Color(0xffEA6B2B),
                            borderRadius: BorderRadius.circular(10.w)
                        ),
                        child: Text('发布视频',style: TextStyle(
                            color: Colors.white,
                            fontSize: 30.sp,
                            fontWeight: FontWeight.w500
                        ),),
                      ),
                    ),
                    SizedBox(height: 40.w,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 30.w,
                          height: 4.w,
                          decoration: BoxDecoration(
                              color: Color(0xff7A7A7A)
                          ),
                        ),
                        SizedBox(width: 30.w,),
                        Text('禁止上传手机号等敏感信息',style: TextStyle(
                            color: Color(0xff7A7A7A),
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w500
                        ),),
                        SizedBox(width: 30.w,),
                        Container(
                          width: 30.w,
                          height: 4.w,
                          decoration: BoxDecoration(
                              color: Color(0xff7A7A7A)
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
          // Visibility(child: DraggableFloatWidget(
          //   child: Container(
          //     height: 100,
          //     width: 100,
          //     decoration: BoxDecoration(
          //         color: defaultBarColor,
          //         borderRadius: BorderRadius.circular(100)
          //     ),
          //     alignment: Alignment.center,
          //     child: Image.asset("assets/fabu/fabu_guide_video.png",width: 100,),
          //   ),
          //   config:  DraggableFloatWidgetBaseConfig(
          //       isFullScreen: true,
          //       initPositionYInTop: false,
          //       initPositionXInLeft: false,
          //       borderTop: 100,
          //       borderBottom: 100
          //   ),
          //   onTap: () {
          //     MediaAssetDataEntity entity = MediaAssetDataEntity();
          //     entity.type=2;
          //     entity.uri = BaseParam.fabuVideoURL;
          //     Navigator.of(context).pushNamed('MediaViewer', arguments: {
          //       'assets': [entity],
          //       'currentIndex': 0
          //     });
          //   },
          // ),visible: BaseParam.fabuVideoURL!=null,)
        ],
      ),
    );
  }
}
